package com.itheima.bos.shiro;


import com.itheima.bos.dao.IUserDao;
import com.itheima.bos.dao.impl.UserDaoImpl;
import com.itheima.bos.domain.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by Mr.King on 2017/3/16.
 */
public class BOSRealm extends AuthorizingRealm{

    //注入dao
    @Autowired
    private IUserDao userDao;


    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("staff");
        return info;
    }

    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken token1 = (UsernamePasswordToken) token;
        String username = token1.getUsername();
        char[] password = token1.getPassword();
        // 根据用户名查询数据库中的密码，将密码交给安全管理器，由安全管理器对象负责比较数据库中的密码和页面传递的密码是否一致
        User user = userDao.findUaerByUsername(username);
        if (user == null){
            return null;
        }
        // 参数一：签名对象，认证通过后，可以在程序的任意位置获取当前放入的对象
        // 参数二：数据库中查询出的密码
        // 参数三：当前realm的类名
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
        return info;
    }
}
